﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Windows.Forms;

namespace Cataloger.Plugins
{
    public class PluginManager
    {
		#region Fields (1) 

        List<AvailablePlugin> availablePlugins = new List<AvailablePlugin>();



		#endregion Fields 

		#region Constructors (1) 

        public PluginManager()
    {
      FindPlugins(Path.Combine(Application.StartupPath,"pluginy"));
    }

		#endregion Constructors 

		#region Properties (1) 

        public List<AvailablePlugin> AvailablePlugins
        {
            get { return availablePlugins; }
            set { availablePlugins = value; }
        }

		#endregion Properties 

		#region Methods (4) 

		// Public Methods (3) 

    public virtual void ClosePlugins()
    {
      foreach (AvailablePlugin pluginOn in availablePlugins)
      {
             
      }
			
      availablePlugins.Clear();
    }

    public virtual void FindPlugins()
    {
      FindPlugins(AppDomain.CurrentDomain.BaseDirectory);
    }

    public virtual void FindPlugins(string Path)
    {
      availablePlugins.Clear();

      foreach (string fileOn in Directory.GetFiles(Path,"*.dll"))
      {
        FileInfo file = new FileInfo(fileOn);
        try
          {
            this.AddPlugin(fileOn);
          }
          catch {}
      }
    }
		// Protected Methods (1) 

    protected virtual void AddPlugin(string FileName)
    {
      Assembly pluginAssembly = Assembly.LoadFrom(FileName);

      foreach (Type pluginType in pluginAssembly.GetTypes())
      {
        if (pluginType.IsPublic)
        {
          if (!pluginType.IsAbstract)
          {
              Type typeInterface = pluginType.GetInterface("Cataloger.Plugins.IPlugin", true);

            if (typeInterface != null)
            {
              AvailablePlugin newPlugin = new AvailablePlugin();
              newPlugin.AssemblyPath = FileName;
              newPlugin.Instance = (IPlugin)Activator.CreateInstance(pluginAssembly.GetType(pluginType.ToString()));
            

              this.availablePlugins.Add(newPlugin);
              newPlugin = null;
            }						
            typeInterface = null;
          }
        }
      }

      pluginAssembly = null;
    }

		#endregion Methods 
    }
}
